import axios, { AxiosResponse, InternalAxiosRequestConfig } from 'axios'
import { Result, ResultCode } from '@src/interfaces/TypeResult'
import TokenUtil from '@util/TokenUtil'
import { ElMessage } from 'element-plus'
import { router } from '@util/RouterUtil.ts'

const ajax = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 10000,
})

// request拦截器
ajax.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    //设置Content-Type
    config.headers['Content-Type'] ||= 'application/json;charset=utf-8'
    // 设置请求头
    const token = TokenUtil.getToken()
    config.headers['Authorization'] ||= token

    return config
  },
  (error: Error) => {
    return Promise.reject(error)
  },
)

// response拦截器
ajax.interceptors.response.use(
  (response: AxiosResponse) => {
    const contentType = response.headers['content-type'] as string
    if (!contentType?.includes('application/json')) {
      return response
    }

    const result = response.data as Result<any>

    if (result.code >= ResultCode.EXCEPTION) {
      ElMessage.error(result.message)

      if (result.code === ResultCode.USER_LOGIN_STATUS_EXCEPTION) {
        TokenUtil.removeToken()
        router.push('/login')
        return Promise.reject(result)
      }

      if (result.code === ResultCode.BACK_ADMIN_LOGIN_STATUS_EXCEPTION) {
        TokenUtil.removeToken()
        router.push('/login/admin')
        return Promise.reject(result)
      }

      return Promise.reject(result)
    }

    return response
  },
  (error: Error) => {
    ElMessage.error('请求出错！')
    return Promise.reject(error)
  },
)

export default ajax
